//
//  GoEasySocketClientListener.swift
//  uwantgoeasy
//
//  Created by 冯传宝 on 12/11/15.
//  Copyright © 2015 uwantsoft. All rights reserved.
//

import Foundation

class GoEasySocketClientListener : SocketClientListener {
    private var goEasy:GoEasy
    private let decoder:GoEasyMessageDecoder = GoEasyMessageDecoder()
    
    init(goEasy: GoEasy){
        self.goEasy = goEasy
    }
    
    func onConnect(){
        goEasy.updateConnectDurationMillis()
        goEasy.login()
    }
    
    func onMessage(msg: [UInt8]){
        let serverMessage:ServerMessage = decoder.decode(msg)
        if let result=serverMessage as? AuthorizeResult{
            goEasy._clientListener.onAuthorizeResult(result)
        }else if let result=serverMessage as? SubscribeResult{
            print("on subscribe result")
            goEasy.subscribeListener(result._channel).onSubscriberResult(result)
        }else if let result=serverMessage as? PublishResult{
            print("on publish result message")
            goEasy.onPublishResult(result)
        }else if let result=serverMessage as? Push{
            print("receive push message")
            goEasy.subscribeListener(result._channel).onReceivedPushMessage(result)
        }else if let result=serverMessage as? UnsubscribeResult{
            print("on Unsubscribe result")
            goEasy.unsubscribeListener(result._channel).onUnsubscribeResult(result)
        }
    }
    
    func onDisconnect(error:UwantSocketError){
        goEasy._clientListener.onDisconnected()
    }
    
    func onConnectFailed(error:UwantSocketError){
        goEasy._clientListener.onConnectFailed(GoEasyError(code: GoEasyErrorCode.UNREACHABLE_TIMEOUT.rawValue, content: "Unreachable or timeout"))
    }
}